import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
# 基类
class Base():
    # 初始化驱动
    def __init__(self,driver):
        self.driver=driver
    # 封装浏览器
    def open_url(self,url):
        self.driver.get(url)
    # 退出浏览器
    def quit(self):
        self.driver.quit()
    # 封装定位元素方法
    def find_element(self,loc):
        try:
            # 显示等待
            WebDriverWait(self.driver,20,0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            # 时间戳
            str = time.strftime('%Y%m%d-%H%M%S')
            # 截图
            self.driver.save_screenshot(str+'.png')
            print(e)
    #封装输入方法
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)
    # 封装点击方法
    def click(self,loc):
        self.find_element(loc).click()
    # 封装文本断言
    def text(self,loc):
        return self.find_element(loc).text

    # 滚动条（执行js代	码）
    # 滚动到任意像素
    def scrollTo(self,x):
        self.driver.switch_to.window('window.scrollTo(0,{x})')
    # 滚动到底部
    def scrollHeight(self):
        self.driver.switch_to.window('window.scrollTo(0,document.body.scrollHeight)')


    # 弹框处理，
    def alert(self):
        self.driver.switch_to.alert.accept()


    # iframe处理，
    def frame(self,loc):
        self.driver.switch_to.frame(self.driver.find_element(*loc))


    # 切换页面，
    def handles(self):
        self.driver.execute_script(self.driver.window_handles[-1])


    # 鼠标事件
    def action_click(self):
        ActionChains(self.driver).click().perform()

    def action_double(self,loc):
        ActionChains(self.driver).double_click().send_keys(loc).perform()


    # 键盘事件，
    def keys_enter(self,loc):
        self.find_element(loc).send_keys(Keys.ENTER)

    def keys_delete(self,loc):
        self.find_element(loc).send_keys(Keys.DELETE)

    def keys_table(self,loc):
        self.find_element(loc).send_keys(Keys.TAB)


    # 浏览器事件，
    def back(self):
        self.driver.back()

    def close(self):
        self.driver.close()

    def refresh(self):
        self.driver.refresh()


    # 下拉框选择
    def select_info(self,index):
        Select(self.driver).select_by_index(index)

    def select_text(self,text):
        Select(self.driver).select_by_visible_text(text)

    def select_value(self,value):
        Select(self.driver).select_by_value(value)


